<template>
    <div>
        <el-card shadow="always" :body-style="{ padding: '40px' }">
            <el-form label-width="80px" :inline="true" size="small">
                <el-form-item label="">
                    <el-input v-model="search"></el-input>
                </el-form-item>
                <el-form-item label="">
                    <el-button type="primary" size="small" icon="el-icon-search" @click="searchBtn">查询</el-button>
                    <el-button type="default" size="small" @click="clear">清空</el-button>
                </el-form-item>
            </el-form>
            <el-button type="primary" size="small" @click="addBtn" v-if="$hideBtn('btn.User.add')">添加</el-button>
            <el-button type="danger" v-if="$hideBtn('btn.User.remove')"  size="small" :disabled="!userIdList.length" @click="deleteMore">批量删除</el-button>

            <el-table :data="userList" border stripe style="margin:20px 0" @selection-change="selectHandler">
                <el-table-column type="selection" align="center">
                </el-table-column>
                <el-table-column label="序号" type="index" align="center" width="60px">
                </el-table-column>
                <el-table-column label="用户名" prop="username" width="150px">
                </el-table-column>
                <el-table-column label="用户昵称" prop="nickName" width="150px">
                </el-table-column>
                <el-table-column label="角色列表" prop="roleName" min-width="250px">
                </el-table-column>
                <el-table-column label="创建时间" prop="gmtCreate" width="200px">
                </el-table-column>
                <el-table-column label="更新时间" prop="gmtModified" width="200px">
                </el-table-column>
                <el-table-column label="操作" width="200px" fixed="right" align="center">
                    <template v-slot="{row,$index}">
                        <el-button type="info" size="mini" v-if="$hideBtn('btn.User.assgin')" icon="el-icon-user-solid" @click="lookBtn(row)"></el-button>
                        <el-button type="primary" size="mini" icon="el-icon-edit-outline" v-if="$hideBtn('btn.User.update')" @click="editBtn(row)">
                        </el-button>
                        <el-popconfirm :title="`是否删除用户 ${row.username} ？`" @confirm="deleteBtn(row.id)">
                            <el-button type="danger" v-if="$hideBtn('btn.User.remove')" style="margin:0 10px" size="mini" slot="reference" icon="el-icon-delete" ></el-button>
                        </el-popconfirm>
                
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination @size-change="sizeChange" @current-change="currentChange" :current-page.sync="currentPage"
                :page-sizes="[2,3,5,7]" :page-size="pageSize" layout="prev, pager, next, jumper,->,sizes,total"
                :total="total" background :pager-count="7">
            </el-pagination>
            <!-- 添加 -->
            <el-dialog title="添加用户" :visible.sync="dialogFormVisible">
                <el-form :model="userInfo" label-width="100px" style="width:90%" ref="formRef" :rules="rules">
                    <el-form-item label="用户名" prop="username">
                        <el-input v-model="userInfo.username" size="small" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="用户昵称" prop="nickName">
                        <el-input v-model="userInfo.nickName" size="small" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="用户密码" prop="password" v-if="!userInfo.id">
                        <el-input v-model="userInfo.password" size="small" autocomplete="off"></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取 消</el-button>
                    <el-button type="primary" @click="save">确 定</el-button>
                </div>
            </el-dialog>
            <!-- 查看对话框 -->
            <el-dialog title="设置角色" :visible.sync="LookDialogVisible">
                <el-form :model="userInfo" label-width="100px" style="width:90%" ref="formRef" :rules="rules">
                    <el-form-item label="用户名" prop="username">
                        <el-input v-model="userInfo.username" size="small" autocomplete="off" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="角色列表" prop="nickName">
                        <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">
                            全选</el-checkbox>
                        <div style="margin: 15px 0;"></div>
                        <el-checkbox-group v-model="roleInfo.roleId" @change="CheckedChange">
                            <el-checkbox v-for="(item,index) in allRolesList" :label="item.id" :key="item.id">
                                {{item.roleName}}</el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取 消</el-button>
                    <el-button type="primary" @click="setRole">确 定</el-button>
                </div>
            </el-dialog>



        </el-card>

    </div>
</template>

<script>
import { nextTick } from 'process';

export default {
    data: () => {
        return {
            search:"",
            userList: [],
            total: 0,
            currentPage: 1,
            pageSize: 5,
            dialogFormVisible: false,
            LookDialogVisible: false,
            userInfo: {
                username: "",
                nickName: "",
                password: ""

            },
            rules: {
                username: [
                    { required: true, message: "用户名必须输入", trigger: "blur" },
                    { min: 4, message: "用户名最少不能小于4个字符", trigger: "change" }
                ],
                password: [
                    { required: true, message: "密码必须输入", trigger: "blur" },
                    { min: 6, message: "密码不能小于6个字符", trigger: "change" }
                ]
            },
            roleInfo: {
                userId: "",
                roleId: []
            },
            // 所有的角色列表
            allRolesList: [],
            isIndeterminate: false,
            checkAll: false,
            userIdList:[],


        }
    },
    components: {},
    methods: {
        async getUserList() {
            let result = await this.$API.user.getUserListRes(this.currentPage, this.pageSize,this.search);
            this.userList = result.data.items;
            this.total = result.data.total;
            console.log(this.userList, this.total);
        },
        // 分页器
        sizeChange(pageSize) {
            this.pageSize = pageSize;
            this.currentPage = 1;
            this.getUserList();
        },
        currentChange() {
            this.getUserList();
        }
        ,
        // 添加按钮
        addBtn() {
            this.dialogFormVisible = true;
            nextTick(() => {
                this.$refs.formRef.resetFields();
                this.userInfo = {}
            })
        },
        // 保存按钮
        save() {
            this.$refs.formRef.validate(async (isTrue) => {
                if (isTrue) {
                    try {
                        await this.$API.user.addUserRes(this.userInfo);
                        this.dialogFormVisible = false;
                        this.getUserList();
                        this.$message.success(this.userInfo.id ? "修改成功" : "添加成功")

                    } catch (error) {
                        this.$message.success(this.userInfo.id ? "修改失败" : "添加失败")
                    }

                }
            })

        },
        // 修改按钮
        editBtn(row) {
            this.dialogFormVisible = true;
            nextTick(() => {
                this.$refs.formRef.resetFields();
                Object.assign(this.userInfo, row)
            })
        },
        // 查看按钮
        async lookBtn(row) {
            Object.assign(this.userInfo, row)
            let result = await this.$API.user.getUserRoleRes(row.id);
            this.roleInfo.userId = row.id;
            this.roleInfo.roleId = result.data.assignRoles.map(item => (item.id));
            this.allRolesList = result.data.allRolesList;
            this.isIndeterminate = this.roleInfo.roleId.length > 0 && this.roleInfo.roleId.length < this.allRolesList.length;
            this.LookDialogVisible = true;

        },
        handleCheckAllChange(flag) {
            let alluserId = this.allRolesList.map(item => item.id)
            this.roleInfo.roleId = flag ? alluserId : [];
            this.isIndeterminate = false;
        },
        CheckedChange(value) {
            this.checkAll = value.length === this.allRolesList.length;
            this.isIndeterminate = value.length > 0 && value.length < this.allRolesList.length;
        },
        // 设置用户角色
        async setRole() {
            let { userId, roleId } = this.roleInfo;
            roleId = roleId.join(",")
            try {
                await this.$API.user.setUserRoleRes(userId, roleId);
                this.getUserList();
                this.LookDialogVisible = false;
                this.$message.success("设置成功")
            } catch (error) {
                this.$message.error("设置失败")
            }

        },
        // 删除单个
        async deleteBtn(id){
            try {
                await this.$API.user.deleteUserRes(id);
                this.getUserList();
                this.$message.success("删除成功")
            } catch (error) {
                this.$message.error("删除失败")
            }
        },
        //搜索按钮
        searchBtn(){
            this.currentPage = 1;
            this.getUserList();
        },
        //清空按钮
        clear(){
            this.search="";
            this.getUserList();
        },
        // 表格选择
        selectHandler(selectArr){
            console.log(selectArr);
            this.userIdList = selectArr.map(item=>item.id);
     
           

        },
        // 批量删除
        async deleteMore(){
             let flag= confirm("是否确认删除？");
             if(!flag)return;
            let arr = [];
            try { 
                this.userIdList.forEach(item=>{
                    arr.push(this.$API.user.deleteUserRes(item));
                })
                await Promise.all(arr);
                this.getUserList();
                this.$message.success("批量删除成功");
                
            } catch (error) {
                this.$message.error("批量删除失败")
            }
        }
    },
    computed: {},
    mounted() {
        this.getUserList();
    }
}
</script>

<style lang="scss" scoped>

</style>